package com.southminority.ethnic.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * Web配置类
 * 
 * @author SouthMinority
 */
@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Autowired
    private TokenAuthenticationInterceptor tokenAuthenticationInterceptor;

    @Autowired
    private AdminAuthenticationInterceptor adminAuthenticationInterceptor;

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOriginPatterns("*")
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .allowedHeaders("*")
                .allowCredentials(true)
                .maxAge(3600);
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 注册Token验证拦截器（优先级高，先执行）
        registry.addInterceptor(tokenAuthenticationInterceptor)
                .addPathPatterns("/**")  // 拦截所有请求
                .excludePathPatterns(   // 排除不需要验证的路径
                    "/user/pagekey",      // 登录
                    "/user/register",     // 获取注册验证码
                    "/user/logon",        // 注册
                    "/user/forgetRegister", // 获取忘记密码验证码
                    "/user/forget",       // 忘记密码
                    "/user/checkToken",   // 检查token
                    "/api/**",            // 前端展示API（不需要token）
                    "/swagger-ui/**",     // Swagger UI
                    "/v3/api-docs/**",    // OpenAPI文档
                    "/error"              // 错误页面
                )
                .order(1); // 设置优先级为1

        // 注册管理员权限验证拦截器（优先级低，后执行）
        registry.addInterceptor(adminAuthenticationInterceptor)
                .addPathPatterns(
                        "/admin/**",
                        "/vipadmin/**",
                        "/aliyunOss/**"
                ).order(2); // 设置优先级为2
    }
}
